/**
 * 考试相关工具函数
 * 提供时间格式化、答案处理等通用功能
 */

// 格式化考试剩余时间显示
export const formatExamTime = (seconds: number): string => {
  if (seconds <= 0) {
    return '00:00:00';
  }
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 根据剩余时间获取颜色状态
export const getTimeStatusColor = (timeLeft: number): string => {
  if (timeLeft <= 300) return '#ff4d4f'; // 5分钟内显示红色 - 紧急
  if (timeLeft <= 1800) return '#faad14'; // 30分钟内显示黄色 - 警告
  return '#52c41a'; // 其他时间显示绿色 - 正常
};

// 获取时间状态文本
export const getTimeStatusText = (timeLeft: number): string => {
  if (timeLeft <= 300) return '即将结束';
  if (timeLeft <= 1800) return '时间紧迫';
  return '时间充足';
};

// 计算答题进度百分比
export const calculateProgress = (completed: number, total: number): number => {
  if (total === 0) return 0;
  return Math.round((completed / total) * 100);
};

// 生成考试答案存储键
export const generateAnswersStorageKey = (paperId: string, userId: string): string => {
  return `exam_answers_${paperId}_${userId}`;
};

// 安全的localStorage操作
export const examStorage = {
  // 保存答案到本地存储
  saveAnswers: (key: string, answers: Record<string, any>): boolean => {
    try {
      localStorage.setItem(key, JSON.stringify(answers));
      return true;
    } catch (error) {
      console.error('保存答案到本地存储失败:', error);
      return false;
    }
  },

  // 从本地存储加载答案
  loadAnswers: (key: string): Record<string, any> | null => {
    try {
      const savedAnswers = localStorage.getItem(key);
      return savedAnswers ? JSON.parse(savedAnswers) : null;
    } catch (error) {
      console.error('从本地存储加载答案失败:', error);
      return null;
    }
  },

  // 清除本地存储的答案
  clearAnswers: (key: string): boolean => {
    try {
      localStorage.removeItem(key);
      return true;
    } catch (error) {
      console.error('清除本地存储失败:', error);
      return false;
    }
  }
};

// 验证考试时间有效性
export const validateExamTime = (startTime: string | null, endTime: string | null) => {
  const now = new Date();
  const start = startTime ? new Date(startTime) : null;
  const end = endTime ? new Date(endTime) : null;
  
  if (start && now < start) {
    return { valid: false, reason: '考试还未开始' };
  }
  
  if (end && now > end) {
    return { valid: false, reason: '考试已结束' };
  }
  
  return { valid: true };
};

// 检查答案完整性
export const checkAnswerCompletion = (answer: any, type: 'question' | 'problem'): boolean => {
  if (!answer) return false;
  
  if (type === 'question') {
    return !!answer.questionAnswer;
  } else {
    return !!(answer.problemAnswer?.code?.trim());
  }
};

// 计算实际考试用时（分钟）
export const calculateExamDuration = (startTime: Date, endTime: Date = new Date()): number => {
  const diffMs = endTime.getTime() - startTime.getTime();
  return Math.round(diffMs / (1000 * 60)); // 转换为分钟
}; 